import sqlite3
from contextlib import closing

from flask import Flask, g, render_template, session, abort, request, flash, redirect, url_for
from flask_login import UserMixin, LoginManager, login_user, logout_user, login_required
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import and_

SQLALCHEMY_DATABASE_URI='sqlite:///flask.db'
DEBUG = True
SECRET_KEY = 'development key'
USERNAME = 'admin'
PASSWORD = 'admin'
SQLALCHEMY_TRACK_MODIFICATIONS=True

app=Flask(__name__)
app.config.from_object(__name__)
app.config.from_envvar('FLASKR_SETTINGS', silent=True)

login_manager=LoginManager()
login_manager.init_app(app)
db=SQLAlchemy(app)

login_manager.login_view='login'
login_manager.login_message = u"请先登录后操作！"
login_manager.session_protection='strong'

class Entries(db.Model):
    id=db.Column(db.Integer,primary_key=True)
    title=db.Column(db.String(50))
    text=db.Column(db.String(50))

    def __init__(self,title,text):
        self.title=title
        self.text=text

    def __repr__(self):
        return  'Entries %s'%self.title



class User(db.Model,UserMixin):
    uid = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(50))
    pwd = db.Column(db.String(50))

    def __init__(self,name,pwd):
        self.id=chr(self.uid)
        self.name=name
        self.pwd =pwd

    def get_id(self):
        return  self.uid

    def __repr__(self):
        return 'User %s'%self.name


@login_manager.user_loader
def load_user(userid):
    return User.query.get(userid)


@app.route('/')
def show_entries():
    return  render_template('show_entries.html',entries=Entries.query.all())


@app.route('/add', methods=['POST','GET'])
@login_required
def add_entry():
    if not session.get('logged_in'):
        abort(401)
    e=Entries(request.form['title'],request.form['text'])
    db.session.add(e)
    try:
        db.session.commit()
    except:
        db.session.rollback()
    flash('New entry was successfully posted')
    return redirect(url_for('show_entries'))


@app.route('/login', methods=['GET', 'POST'])
def login():
    error = None
    if request.method == 'POST':
        user=db.session.query(User).filter(and_(User.name==request.form['username'], User.pwd==request.form['password'])).first()
        if request.form['username'] != app.config['USERNAME']:
            error = 'Invalid username'
        elif request.form['password'] != app.config['PASSWORD']:
            error = 'Invalid password'
        else:
            session['logged_in'] = True
            login_user(user,remember=True)
            flash('You were logged in')

            return redirect(url_for('show_entries'))
    return render_template('login.html', error=error)

@app.route('/logout')
@login_required
def logout():
    #session.pop('logged_in', None)
    logout_user()
    flash('You were logged out')
    return redirect(url_for('show_entries'))

@app.route('/clean')
@login_required
def clean():
    num_rows_deleted = db.session.query(Entries).delete()
    db.session.commit()
    return  redirect(url_for('show_entries'))



if __name__ == '__main__':
    db.create_all()

    app.run()
